package android.demo.xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

public class PullParseService {

	public static List<Book> getBooks(InputStream inputStream) throws Exception {  
		List<Book> books = null;  
		Book book = null;  
		XmlPullParser parser = Xml.newPullParser();  
		parser.setInput(inputStream, "UTF-8");  

		int event = parser.getEventType(); //产生第一个事件  
		while (event != XmlPullParser.END_DOCUMENT) {  
			switch (event) {  
				case XmlPullParser.START_DOCUMENT: //判断当前事件是否是文档开始事件  
					books = new ArrayList<Book>(); //初始化books集合  
					break;  
				case XmlPullParser.START_TAG: //判断当前事件是否是标签元素开始事件  
					if ("book".equals(parser.getName())) { //判断开始标签元素是否是book  
						book = new Book();  
						book.setId(Integer.parseInt(parser.getAttributeValue(0))); //得到book标签的属性值，并设置book的id  
					}  
					if (book!=null) {  
						if ("name".equals(parser.getName())) { //判断开始标签元素是否是name  
							book.setName(parser.nextText());  
						} else if ("price".equals(parser.getName())){ //判断开始标签元素是否是price  
							book.setPrice(Float.parseFloat(parser.nextText()));  
						}  
					}  
					break;  
				case XmlPullParser.END_TAG: //判断当前事件是否是标签元素结束事件  
					if ("book".equals(parser.getName())) { //判断结束标签元素是否是book  
						books.add(book); //将book添加到books集合  
						book = null;  
					}  
					break;  
			}  
			event = parser.next();//进入下一个元素并触发相应事件  
		}//end while  
		return books;  
	} 
	
	public static void testPull() throws Exception{  
		InputStream input = PullParseService.class.getResourceAsStream("book.xml");  
		PullParseService pull = new PullParseService();  
		List<Book> books = pull.getBooks(input);  
		for (Book book : books){  
			Log.i("PULL　XML", book.toString());  
		}  
	} 

}


class Book {
	
	private int id;  
	private String name;  
	private float price;  
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	  
	public String toString(){  
		return this.id+":"+this.name+":"+this.price;  
	}  
}  
